/*
 * 文件名：ExceptionHandler.java
 * 版权：MoonBox 
 * 修改人：Peter
 * 修改时间：2018年9月29日
 * 修改内容：新增
 */
package com.renzhebiao.lkang.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;

import lombok.extern.log4j.Log4j;

/**
 * <p>
 * 
 * @author Peter
 * @since 1.0.0
 */
@Component
@Log4j
public class ExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception exception) {
        log.error("ExceptionHandler 捕获的异常：", exception);
        ModelAndView mv = new ModelAndView();
        /* 使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常 */
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("code", "1000001");
        attributes.put("msg", exception.getMessage());
        view.setAttributesMap(attributes);
        mv.setView(view);
        log.debug("异常:" + exception.getMessage(), exception);
        return mv;

        // String requestType = request.getHeader("X-Requested-With");
        // String type = "api"; // TODO:
        // if (!type.equals("api") && Strings.isNullOrEmpty(requestType)) {
        // // 非API请求
        // return new ModelAndView("redirect:/500.html");
        // } else {// JSON格式返回
        // String json = JSON.toJSONString(ExecuteResult.fail(-1, exception.getMessage()));
        // response.setCharacterEncoding("UTF-8");
        // response.setContentType("application/json; charset=utf-8");
        // try {
        // response.getWriter().write(json);
        // response.getWriter().flush();
        // return null;
        // } catch (IOException e) {
        // log.error("", e);
        // }
        // }
        // return new ModelAndView("redirect:/500.html");
    }

}
